import {Component, ViewChild, enableProdMode} from '@angular/core';
import {Platform, ionicBootstrap} from 'ionic-angular';
import {StatusBar, Splashscreen} from 'ionic-native';

import {Backend} from './providers/backend';

import {GuidePage} from './pages/guide/guide';
// import {TabsPage} from './pages/tabs/tabs';

@Component({
  template: '<ion-nav #appNav [root]="rootPage"></ion-nav>',
  queries: {
    appNav: new ViewChild('appNav')
  },
})
export class AppRoot {

  static get parameters() {
    return [[Platform]];
  }

  constructor(platform) {

    this.platform = platform;

    this.rootPage = GuidePage;

    platform.ready().then(() => {
      console.log('device ready');
      StatusBar.styleDefault();
      Splashscreen.hide();
    });

    this.attachBack();
  }

  attachBack() {
    let exitGuard = 0;

    this.platform.registerBackButtonAction(() => {
      console.log('back clicked');
      console.log(this.appNav.getActive());

      if(this.appNav.canGoBack()) {
        exitGuard = 0;
        console.log('go pop');
        this.appNav.pop();
      } else {
        console.log('go no pop');
        if(this.appNav.getActive() == null || this.appNav.getActive().name != 'TabsPage') {
          return;
        }
        console.log(this.appNav.getActive().instance);
        if(this.appNav.getActive().instance.goBack()) {
          exitGuard = 0;
          return;
        }

        exitGuard++;

        console.log(exitGuard);

        if(exitGuard > 1) {
          console.log('exit app');
          return navigator.app.exitApp();
        } else {
          window.plugins.toast.showShortCenter('Press back again to exit.');
          // this.eliteMart.popupMessage(this.appNav, '再按一次退出');
          setTimeout(() => {
            exitGuard = 0;
            console.log('reset exit guard');
          }, 1000);
        }
      }

    }, 100);
  }
}

enableProdMode();

ionicBootstrap(AppRoot, [Backend], {
  mode: 'ios',
  backButtonText: '',
});

// ionicBootstrap(AppRoot);
